package com.nikmesoft.android.ebox.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;

import com.nikmesoft.android.ebox.models.Lists;
import com.nikmesoft.android.ebox.views.LockPatternView;

public class LockPatternUtil {

	public static final String _Utf8 = "utf-8";
	public static final String _Sha1 = "sha-1";

	public static List<LockPatternView.Cell> stringToPattern(String string) {
		List<LockPatternView.Cell> result = Lists.newArrayList();

		try {
			final byte[] bytes = string.getBytes(_Utf8);
			for (int i = 0; i < bytes.length; i++) {
				byte b = bytes[i];
				result.add(LockPatternView.Cell.of(b / 3, b % 3));
			}
		} catch (UnsupportedEncodingException e) {
		}

		return result;
	}

	public static String patternToString(List<LockPatternView.Cell> pattern) {
		if (pattern == null) {
			return "";
		}
		final int patternSize = pattern.size();

		byte[] res = new byte[patternSize];
		for (int i = 0; i < patternSize; i++) {
			LockPatternView.Cell cell = pattern.get(i);
			res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
		}
		try {
			return new String(res, _Utf8);
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}

	public static String patternToSha1(List<LockPatternView.Cell> pattern) {
		try {
			MessageDigest md = MessageDigest.getInstance(_Sha1);
			md.update(patternToString(pattern).getBytes(_Utf8));

			byte[] digest = md.digest();
			BigInteger bi = new BigInteger(1, digest);
			return String.format((Locale) null,
					"%0" + (digest.length * 2) + "x", bi).toLowerCase();
		} catch (NoSuchAlgorithmException e) {
			return "";
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
}
